package com.team.weigou.utils;

import android.widget.BaseAdapter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.team.weigou.bean.HomeBean;

import java.util.List;

public class HttpTools {

    private static HttpTools tools;

    private HttpTools() {
    }


    public static HttpTools getInstance() {
        if (tools == null) {
            tools = new HttpTools();
        }
        return tools;
    }

    public <T> HttpHandler<String> postDataFromServer(String url, RequestParams params, final BaseAdapter adapter, final List<T> list, final PullToRefreshBase pullToRefreshBase, final boolean isClear, final TypeReference<HomeBean<T>> type) {
        HttpHandler<String> httpHandler = new HttpUtils().send(HttpRequest.HttpMethod.GET, url,params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                HomeBean<T> app = JSONObject.parseObject(responseInfo.result, type);
                if (app != null && app.getData() != null && !app.getData().isEmpty()) {
                    if (isClear) {
                        list.clear();
                    }
                    list.addAll(app.getData());
                    adapter.notifyDataSetChanged();
                }
                pullToRefreshBase.onRefreshComplete();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                pullToRefreshBase.onRefreshComplete();
            }
        });

        return httpHandler;

    }

}
